--
-- Author: songjianbang
-- Date: 2018-8-13 
--
-- RewardFatePanel
local RewardNodeRender = import(".renders.RewardNodeRender")
local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local RewardView = require("app.system.secret.SecretRewardView")
local RewardFatePanel = app.mvc.createPanelClass(...)
local GRes = Res
local Res = {
	RewardFadeNode = "ui2/activity/Node_fate.csb",
	RewardFade1Node = "ui2/activity/Node_fate_1.csb",
}

--data = 
function RewardFatePanel.create(data, node)
	local sprite = RewardFatePanel.extend(node or cc.CSLoader:createNode(Res.RewardFadeNode))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init(data)

	return sprite
end       

function RewardFatePanel:init(data)
	self.super.init(self, data)
	self:setNodeEventEnabled(true)
	
	local rm = app:getInst("RewardModel")
	local m = rm:getFateStoneModel()
	self.model = m
	m:reqRewards()

	self.panel = self:findChild("Panel")
	
	self.titleLbl = self:findChild("Panel/tlt")
	self.stonePanel = self:findChild("Panel/Panel_img")
	self.stonePanel:hide()

	self.countPanel = self:findChild("Panel/Panel_bom/bg_num")
	self.countPanel:setTouchEnabled(true)
	self.countPanel:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:showFateTips()           
        end
	end )
	
	self:findChild("Panel/btn_share"):addClickEventListener(function()
		if self.currentChapter then
			app:sendMsg("PhotoController", "showFatestoneShareView", checknumber(self.currentChapter.index))
		end
	end)

	self.lbtn = self:findChild("Panel/btn_left")
	self.rbtn = self:findChild("Panel/btn_right")
	self.lbtn:setLocalZOrder(1)
	self.rbtn:setLocalZOrder(1)

	self.lbtn:addClickEventListener(function(sender)        
        self:refreshPage(math.max(1, checknumber(self.currentPageIndex) - 1))
	end)
	
	self.rbtn:addClickEventListener(function(sender)        
        self:refreshPage(math.max(1, checknumber(self.currentPageIndex) + 1))
	end)
	
	local s = m:getCurrnetFateStone()

	for i, v in ipairs(s.progresses) do 
		self["r"..tostring(i)] = RewardNodeRender.create(nil, self:findChild("Panel/Panel_bom/reward_"..tostring(i)))
		self["r"..tostring(i)]:onGetRewardClick(function (aID) self:getReward(aID) end)
	end

	local function setdefaultvisible(b)
		self:findChild("Panel/Panel_bg"):setVisible(b)
		self:findChild("Panel/Panel_bom"):setVisible(b)
		self:findChild("Panel/tlt"):setVisible(b)
		self.pv:setVisible(b)		
	end

	local function gotodefaultpage()
		if self.firstload == nil then
			self.firstload = true
			setdefaultvisible(true)
			local rs = m:getFirstRedChapter()
			self:refreshPage(rs.index)
		end
	end

	local this = self
	EM:on(self.model:GetEvtRewardsChangeName(), function(evt, rId)
		this:refreshRewards()
		gotodefaultpage()
	end)
	
	self.pv = ccui.PageView:create()
	self.pv:setContentSize(self.stonePanel:getContentSize())
	self.pv:setAnchorPoint(self.stonePanel:getAnchorPoint())
	self.pv:setPosition(self.stonePanel:getPosition())
	self.pv:setTouchEnabled(true)

	self.pv:setBackGroundColor(display.COLOR_GRAY)
	self.pv:setBackGroundColorType(1)
	self.pv:setCustomScrollThreshold(300)

	self:findChild("Panel"):addChild(self.pv)

	self.pages = {}
	local last = m:getLastFateStone()
	for i = 1, last.index do
		self.pv:addPage(self:loadPage(i))
	end

	self.pv:onEvent(function(a,b,c)
		local curIndex = self.pv:getCurPageIndex() + 1
		if curIndex ~= self.currentPageIndex then
			self:refreshCurrentPage(curIndex)
		end
	end)
	setdefaultvisible(false)
	-- gotodefaultpage()
end


function RewardFatePanel:onExit()
	EM:removeByName(self.model:GetEvtRewardsChangeName())
end

function RewardFatePanel:refreshRewards()
	self.progressCount = 0
	local s = self.currentChapter
	if not s then return end

	local allrewarded = true
	for i, v in ipairs(s.progresses) do 
		local finished = s.finishedCount >= checknumber(v.cfg.progressValue)
		local rewarded = finished and (not self.model:hasRewarded(v.cfg.ID))
		self["r"..tostring(i)]:setData({config = v.cfg, count = v.cfg.progressValue, rewardID=v.cfg.rewardID, finished = finished, rewarded=rewarded})
	
		if finished then
			self.progressCount = self.progressCount + 1
		end

		if not rewarded then
			allrewarded = false
		end
	end

	self:findChild("Panel/Panel_bom/num"):setString(tostring(s.finishedCount))
	self:findChild("Panel/ani"):stopAllActions()
	self:findChild("Panel/ani"):hide()
	if self.model.finishedchapter and self.model.finishedchapter[s.index] and allrewarded then
		self.model.finishedchapter[s.index] = false
		allrewarded = false
		self:playChangeAnimation()
	end

	self:showProgress(allrewarded)
end

function RewardFatePanel:showProgress(allrewarded)
	self:findChild("Panel/btn_share"):setVisible(allrewarded)
	self:findChild("Panel/Panel_bom/bg"):setVisible(not allrewarded)
	local ps = self:findChild("Panel"):getContentSize()
	if allrewarded then
		self:findChild("Panel/Panel_bom"):setPositionX(ps.width*0.417)
	else
		self:findChild("Panel/Panel_bom"):setPositionX(ps.width*0.5)
	end
end

function RewardFatePanel:playChangeAnimation()
	self.ani = self:findChild("Panel/ani")
	self.ani:setTouchEnabled(false)
	self.ani:findChild("Panel"):setTouchEnabled(false)

	local actions = cc.CSLoader:createTimeline("ui2/activity/ani_mysb.csb")
	actions:gotoFrameAndPlay( 0, false )
	local act = cca.seq({cca.delay(0.3),cca.callFunc(function()
        self:showProgress(true)
	end)})
	self:stopAllActions()
	self:runAction(act)

	self.ani:show()
	self.ani:stopAllActions()
	self.ani:runAction(actions)
end

function RewardFatePanel:loadPage(idx)
	local p = ccui.Layout:create()

	p:setBackGroundColor(display.COLOR_BLACK)
	p:setBackGroundColorType(1)

	local csbPath = "ui2/activity/Node_fate_"..tostring(idx)..".csb"
	p.actionNode = cc.CSLoader:createNode(csbPath)
	local sz = self.stonePanel:getContentSize()
	p.actionNode:setPosition(cc.p(sz.width*0.5, sz.height*0.5))
	p:addChild(p.actionNode)
	p.actionNode:stopAllActions()

	p.actions = cc.CSLoader:createTimeline(csbPath)
	p.actions:retain()

	local s = self.model:getChapter(idx)
	self.pauseTo(p, s.finishedCount - checknumber(s.splashCount))

	self.pages[idx] = p

	return p 
end

function RewardFatePanel:refreshCurrentPage(curIndex)
	self.currentPageIndex = curIndex
	if curIndex < 1 or curIndex > self.model.maxChapterIndex then
		return
	end

	local s = self.model:getChapter(curIndex)
	self.currentChapter = s
	self.titleLbl:setString(L("fatestonetips_title"..tostring(s.index)))
	
	self:refreshRewards()

	local p = self.pages[curIndex]
	if checknumber(s.splashCount) > 0 then
		self.splashFateStone(p, s.finishedCount - checknumber(s.splashCount) + 1, s.finishedCount)
	else
		self.pauseTo(p, s.finishedCount)
	end
	s.splashCount = 0

	self:findChild("Panel/Panel_bom/bar/LoadingBar"):setPercent(100*s.finishedCount/7)
	self:refreshPageBtn()
end

function RewardFatePanel:refreshPage(aIndex, aChapter)
	local s = self.model:getChapter(aIndex)

	-- if s.index > self.model:getCurChapterID() then
	-- 	display.pushToast(L("fatestone_notnow"))
	-- 	return
	-- end

	self.pv:moveToPage(aIndex - 1)
	self:refreshCurrentPage(aIndex)
end

function RewardFatePanel:getReward(aID)
	self.model:reqGetReward(aID)
end

function RewardFatePanel:showFateTips()
	local dataTemp = {
		name=L("fatestonetips_title"),
		string1 = L("fatestonetips_desc"),
	}

	if self.eventTips then
		self.eventTips:setData( dataTemp )
	else
		self.eventTips = NewRareInfoView.create()
		self.eventTips:setData( dataTemp )
		self:addChild( self.eventTips )

		local triggerNodeBoundingBox = self.countPanel:getBoundingBox()
		local worldPosTemp = self.countPanel:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
		triggerNodeBoundingBox.x = worldPosTemp.x
		triggerNodeBoundingBox.y = worldPosTemp.y
		display.adjustNodePos( triggerNodeBoundingBox, self.eventTips , -66, 5)

		-- 点击空白区域关闭
		display.nodeRemoveForNotHit(self.eventTips, function()
			if self.eventTips then
				self.eventTips:removeFromParent()
				self.eventTips = nil
			end
		end)
	end
end

function RewardFatePanel:refreshPageBtn()
	self.lbtn:show()
	self.rbtn:show()

	if self.currentChapter.index == 1 then
		self.lbtn:hide()
	end

	if self.currentChapter.index >= self.model.maxChapterIndex then
		self.rbtn:hide()
	end
end

function RewardFatePanel:pauseTo(i)
	local a = nil
	local actionName = "1"
	if i > 0 then
		actionName = tostring(i)
	end
	if self.actions:IsAnimationInfoExists(actionName) then
		a = self.actions:getAnimationInfo(actionName)
	end	
	
	if a then
		if i == 0 then
			self.actions:gotoFrameAndPlay(a.startIndex, a.startIndex, false)	
		else
			self.actions:gotoFrameAndPlay(a.endIndex-1, a.endIndex, false)	
		end		
	end
	
	self.actionNode:stopAllActions()
	self.actionNode:runAction(self.actions)
end

function RewardFatePanel:splashFateStone(b, e)
	local ab = nil
	local ae = nil
	if self.actions:IsAnimationInfoExists(tostring(b)) then
		ab = self.actions:getAnimationInfo(tostring(b))
	end	
	if self.actions:IsAnimationInfoExists(tostring(e)) then
		ae = self.actions:getAnimationInfo(tostring(e))
	end
	
	if ab and ae then
		self.actions:gotoFrameAndPlay(ab.startIndex-1, ae.endIndex, ab.startIndex-1, false)	
	end

	self.actionNode:stopAllActions()
	self.actionNode:runAction(self.actions)
end

function RewardFatePanel:refresh()
	if self._data then
	end
end

function RewardFatePanel:onBtnClick(cb)
	self._onBtnClick = cb
end

function RewardFatePanel:onOperate()
end

return RewardFatePanel